﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Meqs.Entity;
using System.Collections.Generic;
using Meqs.Logic.Interface;
using System.Web.Services;
using Meqs.Utilities;


public partial class Base_School_ClassCauseTeacher : System.Web.UI.Page
{
    /// <summary>
    /// 学校开设课程
    /// </summary>
    protected List<GlobalCauseInfo> schoolglobalCause = new List<GlobalCauseInfo>();
    /// <summary>
    /// 学校的年级
    /// </summary>
    protected List<int> grades = new List<int>();
    /// <summary>
    /// 学校的年级
    /// </summary>
    protected List<string> gradename = new List<string>();
    /// <summary>
    /// 班级列表
    /// </summary>
    protected IList<ClsInfo> cls = null;
    /// <summary>
    /// 教研组教师列表
    /// </summary>
    protected Hashtable subjectTeacher = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            SchoolInfo si = SchoolCommon.Sch_SchoolInfo;
            grades = Common.GetGradeList(si.SchoolOpt);
            gradename.Clear();
            foreach (int i in grades)
            {
                gradename.Add(Common.ConvertGradeNum(i));
            }

        }

    }

    protected string GetInit()
    {
        string str = "";
        str += "var sel = document.getElementById('gradesel');";
        for(int i=0;i<grades.Count;i++)
        {
            str += "var oOption = document.createElement('OPTION');";
            str +="oOption.text = '" + gradename[i] + "';oOption.value = " + grades[i] + ";";
            if(0 == i)
            {
                str += "oOption.selected = true;";
                str += "document.getElementById('textGrade').value = '" + grades[i] + "';";
            }
            else
            {
                str += "oOption.selected = false;";
            }
            str += "sel.add(oOption);";
        }
        
        return str;
    }
    private bool CheckIn(List<CauseInfo> SchoolCause,int causeid)
    {
        foreach (CauseInfo c in SchoolCause)
        {
            if (c.RID == causeid)
                return true;
        }
        return false;
    }
    protected void btnBind_Click(object sender, EventArgs e)
    {
        SchoolInfo si = SchoolCommon.Sch_SchoolInfo;
        Hashtable htParam = new Hashtable();
        htParam.Add("IsEffect", 1);
        List<GlobalCauseInfo> globalCause = (List<GlobalCauseInfo>)Container<IGlobalCauseInfoLogic>.Instance.FindAll(htParam);

        Hashtable ht = new Hashtable();
        //根据学校标识，查询学校的课程ID
        ht.Clear();
        ht.Add("SchoolMark", Common.GetConstSchoolMark());

        List<CauseInfo> SchoolCause = (List<CauseInfo>)Container<ICauseInfoLogic>.Instance.FindAll(ht);
        ht.Clear();
        ht.Add("SchoolMark", Common.GetConstSchoolMark());
        ht.Add("Grade", Convert.ToInt32(textGrade.Text));
        IList<CouseGradeInfo> couinfo = Container<ICouseGradeInfoLogic>.Instance.FindAll(ht);

        foreach (GlobalCauseInfo g in globalCause)
        {
            if (CheckIn(SchoolCause, g.RID))
            {
                bool add = false;
                foreach (CouseGradeInfo cgi in couinfo)
                {
                    if (cgi.CourseID == g.RID)
                    {
                        add = true;
                        break;
                    }
                }
                if (add)
                {
                    schoolglobalCause.Add(g);
                }
            }
        }
        htParam = new Hashtable();
        htParam.Add("SchoolMark", si.SchoolMark);
        IList<TeacherInfo> ti = Container<ITeacherInfoLogic>.Instance.FindAll(htParam);

        IList<TeachClsCause> tcc = Container<ITeachClsCauseLogic>.Instance.FindAll(null);
        htParam = new Hashtable();
        htParam.Add("Grade", Convert.ToInt32(textGrade.Text));
        htParam.Add("SchoolYear",si.SchoolYear);
        //htParam.Add("Term", si.SchoolTerm);
        htParam.Add("SchoolMark", si.SchoolMark);
        IList<GradeGroup> gg = Container<IGradeGroupLogic>.Instance.FindAll(htParam);
        subjectTeacher = new Hashtable();
        for (int i = 0; i < schoolglobalCause.Count;i++ )
        {
            List<ViewClassTeacher> temp = new List<ViewClassTeacher>();
            foreach(TeachClsCause t in tcc)
            {
                if (t.CauseID == schoolglobalCause[i].RID)
                {
                    foreach (GradeGroup g in gg)
                    {
                        if(g.Grade == Convert.ToInt32(textGrade.Text) && g.TeacherID == t.TeachID)
                        {
                            TeacherInfo tinfo = GetTeacherInfo(ti,g.TeacherID);
                            if (tinfo != null)
                            {
                                ViewClassTeacher v = new ViewClassTeacher();
                                v.grade = g.Grade;
                                v.name = tinfo.TeachName;
                                v.no = tinfo.TeachCode;
                                v.rid = tinfo.RID;
                                v.teachclass = GetTeachID(g.TeacherID, tcc, schoolglobalCause[i].RID);
                                temp.Add(v);
                            }
                        }
                    }

                }
            }

            subjectTeacher.Add(schoolglobalCause[i].RID, temp);
        }

        htParam = new Hashtable();
        htParam.Add("IsEffect", 1);
        htParam.Add("Grade", Convert.ToInt32(textGrade.Text));
        cls = Container<IClsInfoLogic>.Instance.FindAll(htParam);
        Repeater1.DataSource = cls;
        Repeater1.DataBind();

    }
    private List<int> GetTeachID(int id, IList<TeachClsCause> tcc,int causeid)
    {
        List<int> clses = new List<int>();
        foreach (TeachClsCause t in tcc)
        {
            if (id == t.TeachID && causeid == t.CauseID && t.ClsID != 0)
            {
                clses.Add(t.ClsID);
            }
        }
        return clses;
    }
    private TeacherInfo GetTeacherInfo(IList<TeacherInfo> ti ,int id)
    { 
        foreach(TeacherInfo t in  ti)
        {
            if(t.RID == id)
            {
                return t;
            }
        }
        return null;
    }

    private bool CheckIn(int id, List<ViewClassTeacher> temp)
    { 
        foreach(ViewClassTeacher t in temp)
        {
            if (id == t.rid)
            {
                return true;
            }
        }
        return false;
    }
    protected string GetHeader()
    {
        int w = 100 / (1 + schoolglobalCause.Count);
        string header = "<table id='settingTable' border=0 cellpadding=0 cellspacing=1   class='useList1' style='width:" + (100 + schoolglobalCause.Count * 100) + "px;'><th class='FixedRow' style='text-align:center;padding-left: 5px;width:100px'>班级</th>";
        foreach (GlobalCauseInfo g in schoolglobalCause)
        {
            header += "<th  style='text-align:center;padding-left: 5px;width:100px;' class='FixedRow'>" + g.CauseName + "</th>";
        }
        return header;
    }
    protected int Classindex = 0;

    protected string GetClassInfo(int rid,string  ClsName)
    {
        int w = 100 / (1 + schoolglobalCause.Count);

        string content = "<tr ><td  style='text-align:center;padding-left: 5px;' >" + ClsName + "</td>";
        foreach (GlobalCauseInfo g in schoolglobalCause)
        {
            string ClassSubjInfo = "";
            content += "<td {clsinfoinfo}  style='text-align:center;padding-left: 5px;'>";
            
            List<ViewClassTeacher> temp = subjectTeacher[g.RID] as List<ViewClassTeacher>;
            content += "<select  onchange='teacherChange(this)'>";
            List<int> teacherids = new List<int>();
            bool have = false;
            int ttid = 0;
            foreach(ViewClassTeacher vc in temp)
            {
                if (!teacherids.Contains(vc.rid))
                {
                    
                    teacherids.Add(vc.rid);
                    string sub = GetSelected(rid, vc.teachclass);
                    content += "<option " + sub + " value='" + vc.rid + "'>" + vc.name + "</option>";
                    if (sub == "selected")
                    {
                        have = true;
                        ttid = vc.rid;
                    }
                }
            }
            content += "<option " + ( have == false ? "selected":"") + " value='0'>(无)</option>";
            content += "</select>";
            content += "</td>";
            ClassSubjInfo += "ClassID=" + rid + " ";
            ClassSubjInfo += "CauseID=" + g.RID + " ";
            ClassSubjInfo += "TeacherID=" + ttid + " ";
            content = content.Replace("{clsinfoinfo}", ClassSubjInfo);
        }
        content += "</tr>";
        return content;
    }
    private string GetSelected(int rid,List<int> classesid)
    { 
        foreach(int i in classesid)
        {
            if(i==rid)
            {
                return "selected";
            }
        }
        return "";
    }

    [WebMethod]
    public static int DoSave(ClassTeacherinfo[] infos)
    {
        List<int> temp = GetClassID(infos);
        Hashtable table = new Hashtable();
        table.Add("RID", RoleKeyEnum.Class_Teacher);
        IList<SecurityRole> sr = Container<ISecurityRoleLogic>.Instance.FindAll(table);
        IList<TeacherRoles> tr = new List<TeacherRoles>();
        SchoolInfo si = SchoolCommon.Sch_SchoolInfo;
        if (sr.Count > 0)
        {
            table = new Hashtable();
            
            table.Add("SchoolMark", si.SchoolMark);
            table.Add("SchoolYear", si.SchoolYear);
            table.Add("Term", si.SchoolTerm);
            table.Add("RoleID", sr[0].RID);
            tr = Container<ITeacherRolesLogic>.Instance.FindAll(table);
        }
         
        foreach(int id in temp)
        {
            Hashtable ht = new Hashtable();
            ht.Add("ClsID",id);
            Container<ITeachClsCauseLogic>.Instance.DeleteClsCauseTeacher(ht);
        }
        foreach (ClassTeacherinfo ct in infos)
        {
            if (ct.TeacherID!=0)
            {
                TeachClsCause tcc = new TeachClsCause();
                tcc.CauseID = ct.CauseID;
                tcc.ClsID = ct.ClassID;
                tcc.TeachID = ct.TeacherID;
                Container<ITeachClsCauseLogic>.Instance.InsertTeachClsCause(tcc);
                if (sr.Count > 0)
                {
                    if (!FindTeach(tr, ct.TeacherID))
                    {
                        TeacherRoles ttr = new TeacherRoles();
                        ttr.RoleID = sr[0].RID;
                        ttr.SchoolMark = si.SchoolMark;
                        ttr.SchoolYear = si.SchoolYear;
                        ttr.TeacherID = ct.TeacherID;
                        ttr.Term = si.SchoolTerm;
                        int newid = Container<ITeacherRolesLogic>.Instance.Create(ttr);
                        ttr.RID = newid;
                        tr.Add(ttr);
                    }
                }
            }
        }

        string classidss="-1";
        table = new Hashtable();
        table.Add("IsEffect", 1);
        table.Add("SchoolMark", si.SchoolMark);
        IList<ClsInfo> mycls = Container<IClsInfoLogic>.Instance.FindAll(table);
        foreach(ClsInfo cls in mycls)
        {
            classidss += ","+cls.RID;
        }
        table = new Hashtable();
        table.Add("ClsIDs", classidss);
        IList<TeachClsCause> ttcc = Container<ITeachClsCauseLogic>.Instance.FindAll(table);
        foreach(TeacherRoles ttr in tr)
        {
            if (!CheckTeach(ttr.TeacherID, ttcc))
            {
                table = new Hashtable();
                table.Add("RID", ttr.RID);
                Container<ITeacherRolesLogic>.Instance.DeleteBy(table);
            }
        }
        return 0;
    }
    private static bool CheckTeach(int teachid, IList<TeachClsCause> ttcc)
    { 
        foreach(TeachClsCause t in ttcc)
        {
            if (t.TeachID == teachid)
            {
                return true;
            }
        }
        return false;
    }
    private static bool FindTeach(IList<TeacherRoles> tr, int id)
    {
        foreach (TeacherRoles t in tr)
        { 
            if(t.TeacherID == id)
            {
                return true;
            }
        }
        return false;
    }
    private static List<int> GetClassID(ClassTeacherinfo[] infos)
    {
        List<int> classids = new List<int>();
        foreach (ClassTeacherinfo i in infos)
        {
            if (!classids.Contains(i.ClassID))
            {
                classids.Add(i.ClassID);
            }
        }
        return classids;
    }
    [System.Web.Services.WebMethod]
    public static List<TeacherRoles> GetTeacherRoles()
    {
        SchoolInfo si = SchoolCommon.Sch_SchoolInfo;
        ITeacherRolesLogic Logic = Container<ITeacherRolesLogic>.Instance;
        List<TeacherRoles> rolesList = (List<TeacherRoles>)Logic.FindTeacherLeader(Common.GetConstSchoolMark(), si.SchoolYear,si.SchoolTerm);
        return rolesList;
    }
    [System.Web.Services.WebMethod]
    public static List<GlobalCauseInfo> GetCauses()
    {

        SchoolInfo si = SchoolCommon.Sch_SchoolInfo;
        Hashtable htParam = new Hashtable();
        htParam.Add("IsEffect", 1);
        List<GlobalCauseInfo> globalCause = (List<GlobalCauseInfo>)Container<IGlobalCauseInfoLogic>.Instance.FindAll(htParam);
        string temp_path = HttpContext.Current.Server.MapPath("../../");
        string save_path = temp_path + "\\download\\" + "导入领导模版.xls";
        HttpContext.Current.Session["filepath"] = save_path;
        return globalCause;
    }
    [WebMethod]
    public static string GetExcel1(ExcelTableCell[][] cells)
    {
        string temp_path = HttpContext.Current.Server.MapPath("../../");
        string save_path = temp_path + "download\\" + DateTime.Now.Ticks.ToString() + "_profile.xls";
        HttpContext.Current.Session["filepath"] = save_path;
        ExcelUtil.ExcelExport(save_path, DateTime.Now.Ticks.ToString() + "教学领导", 0, 0, cells);
        return "";
    }
    [WebMethod]
    public static string GetExcel(ExcelTableCell[][] cells,int grade)
    {
        
        Hashtable ht = new Hashtable();
        ht.Add("Grade", grade);
        ht.Add("SchoolMark", Common.GetConstSchoolMark());
        ht.Add("IsEffect", 1);
        IList<VClsInfo> vc =  Container<IClsInfoLogic>.Instance.FindClassInfo(ht);

        for (int i = 0; i < cells[1].Length; i++)
        { 
            foreach(VClsInfo c in vc)
            {
                if (cells[0][i].Text == c.ClsGradeName)
                {
                    cells[1][i].Text = c.Header;
                }
            }
            
        }
        string temp_path = HttpContext.Current.Server.MapPath("../../");
        string save_path = temp_path + "\\download\\" + "导入模版.xls";
        HttpContext.Current.Session["filepath"] = save_path;
        Meqs.Utilities.ExcelUtil.ExcelExport(save_path, Common.ConvertGradeNum(grade), 1, 0, cells);
        return "";
    }
}

public class ViewClassTeacher
{
    public string name;
    public string no;
    public int rid;
    public int grade;
    public List<int> teachclass = new List<int>();
}

public class ClassTeacherinfo
{
    private int teacherid = 0;
    public int TeacherID
    {
        get { return teacherid; }
        set { teacherid = value; }
    }
    private int classid = 0;
    public int ClassID
    {
        get { return classid; }
        set { classid = value; }
    }
    private int causeid = 0;
    public int CauseID
    {
        get { return causeid; }
        set { causeid = value; }
    }
}